package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.bean.RecordBean;
import flc.ast.databinding.ActivityAudioFormatBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioFormat;
import stark.common.basic.media.video.VideoFormat;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.WorkPathUtil;

public class AudioFormatActivity extends BaseAc<ActivityAudioFormatBinding> {

    public static String audioPath;
    private String selFormat = "", newName = "";
    private Dialog myRenameDialog, myFormatTurnDialog;
    private TextView dialogFormatTurnTitle, dialogFormatTurnText, dialogFormatPro, dialogFormatTurnComp;
    private ProgressBar pbFormat;
    private EditText dialogRename;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private long audioLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvAudioSbLeft.setText(TimeUtil.getMmss(mediaPlayer.getCurrentPosition()));
//            mDataBinding.sbAudio.setProgress(Integer.parseInt(TimeUtils.millis2String(mediaPlayer.getCurrentPosition(), "ss")));
            mDataBinding.sbAudio.setProgress(mediaPlayer.getCurrentPosition());
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_format;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);
        mDataBinding.ivAudioFormatBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivAudioPlay.setOnClickListener(this);
        mDataBinding.tvFormatAac.setOnClickListener(this);
        mDataBinding.tvFormatFlac.setOnClickListener(this);
        mDataBinding.tvFormatM4a.setOnClickListener(this);
        mDataBinding.tvFormatMp3.setOnClickListener(this);
        mDataBinding.tvFormatWav.setOnClickListener(this);
        mDataBinding.llFileName.setOnClickListener(this);
        mDataBinding.tvAudioFormatStart.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAudioPlay:
                if (mediaPlayer.isPlaying()) {
                    mDataBinding.ivAudioPlay.setImageResource(R.drawable.bofang1);
                    mediaPlayer.pause();
                    stopTime();
                } else {
                    mDataBinding.ivAudioPlay.setImageResource(R.drawable.zanting1);
                    mediaPlayer.start();
                    startTime();
                }
                break;
            case R.id.tvFormatAac:
                clearFormat();
                mDataBinding.tvFormatAac.setBackgroundResource(R.drawable.kk2);
                selFormat = "aac";
                break;
            case R.id.tvFormatMp3:
                clearFormat();
                mDataBinding.tvFormatMp3.setBackgroundResource(R.drawable.kk2);
                selFormat = "mp3";
                break;
            case R.id.tvFormatFlac:
                clearFormat();
                mDataBinding.tvFormatFlac.setBackgroundResource(R.drawable.kk2);
                selFormat = "flac";
                break;
            case R.id.tvFormatM4a:
                clearFormat();
                mDataBinding.tvFormatM4a.setBackgroundResource(R.drawable.kk2);
                selFormat = "m4a";
                break;
            case R.id.tvFormatWav:
                clearFormat();
                mDataBinding.tvFormatWav.setBackgroundResource(R.drawable.kk2);
                selFormat = "wav";
                break;
            case R.id.llFileName:
                renameDialog();
                myRenameDialog.show();
                break;
            case R.id.ivDialogFormatRenameCancel:
                myRenameDialog.dismiss();
                break;
            case R.id.ivDialogFormatRenameConfirm:
                newName = dialogRename.getText().toString();
                mDataBinding.tvFileName.setText(newName);
                myRenameDialog.dismiss();
                break;
            case R.id.tvAudioFormatStart:
                formatTurnDialog();
                startConv();
                break;
            case R.id.tvDialogFormatTurnComp:
                myFormatTurnDialog.dismiss();
                startActivity(HomeActivity.class);
                finish();
                break;
        }
    }

    @Override
    protected void initData() {
        audioLength = MediaUtil.getDuration(audioPath);
        try {
            setMedia();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String fileName = FileUtils.getFileName(audioPath);
        int index = fileName.indexOf(".");
        String startFormat = fileName.substring(index + 1, fileName.length());
        mDataBinding.tvFileName.setText(getString(R.string.please_input_name));
        mDataBinding.tvStartFormat.setText(getString(R.string.play_format_text2) + startFormat);
    }

    private void setMedia() throws IOException {
        mHandler = new Handler();
        //设置seekbar
//        mDataBinding.sbAudio.setMax(Integer.parseInt(TimeUtils.millis2String(audioLength, "ss")));
        mDataBinding.sbAudio.setMax((int) audioLength);
        mDataBinding.tvAudioSbLeft.setText("00:00");
        mDataBinding.tvAudioSbRight.setText(TimeUtil.getMmss(audioLength));
        mDataBinding.sbAudio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
        mediaPlayer.setDataSource(audioPath);
        mediaPlayer.prepare();
        mediaPlayer.seekTo(1);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvAudioSbLeft.setText("00:00");
                mDataBinding.sbAudio.setProgress(0);
                mDataBinding.ivAudioPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    //开始转换
    private void startConv() {
        if (TextUtils.isEmpty(selFormat)) {
            ToastUtils.showShort(R.string.please_sel_format);
        } else if (TextUtils.isEmpty(newName)) {
            ToastUtils.showShort(R.string.please_input_name);
        } else {
            mDataBinding.tvAudioFormatStart.setEnabled(false);
            //整理参数
            String format = getFormat();
            comAudio(format);//修改参数其实就是压缩视频
        }
    }

    //开始转换
    private void comAudio(String format) {
        myFormatTurnDialog.show();
        String audioOutPath = WorkPathUtil.generateAudioFilePathByName(newName + format);
        EpEditor.audioFormatConvert(audioPath, audioOutPath, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDataBinding.tvAudioFormatStart.setEnabled(true);
                        saveVideo(audioOutPath, format);
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myFormatTurnDialog.dismiss();
                        mDataBinding.tvAudioFormatStart.setEnabled(true);
                        ToastUtils.showShort(R.string.conv_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                pbFormat.setProgress((int) (progress * 100));
                dialogFormatPro.setText(new DecimalFormat(getString(R.string.unit_num1)).format(progress * 100) + getString(R.string.unit_percent));
                if (progress * 100 == 100) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialogFormatTurnComp.setVisibility(View.VISIBLE);
                            dialogFormatTurnTitle.setText(getString(R.string.format_comp_title));
                            dialogFormatTurnText.setText(getString(R.string.format_comp_tip));
                        }
                    });
                }
            }
        });
    }

    //保存视频
    private void saveVideo(String path, String format) {
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String filePath = FileUtil.generateFilePath(Content.myTemp, format);
                FileUtils.copy(path, filePath);
                emitter.onNext(filePath);
            }

            @Override
            public void accept(String savePath) {
                //重命名
                FileUtils.rename(savePath, newName + format);
                String newPath = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + newName + format;
                //保存到相册
                saveRecord(newPath, 100, true);
                FileP2pUtil.copyPrivateAudioToPublic(mContext, newPath);
                mDataBinding.tvAudioFormatStart.setEnabled(true);
            }
        });
    }

    private void saveRecord(String audioPath, int progress, boolean isComp) {
        List<RecordBean> listSave = new ArrayList<>();
        listSave.add(new RecordBean(audioPath, FileUtils.getFileName(audioPath), selFormat, progress, isComp, false, R.drawable.yinpin1));
        List<RecordBean> listSp = SPUtil.getObject(mContext, new TypeToken<List<RecordBean>>() {
        }.getType());
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            SPUtil.putObject(mContext, listSp, new TypeToken<List<RecordBean>>() {
            }.getType());
        } else {
            SPUtil.putObject(mContext, listSave, new TypeToken<List<RecordBean>>() {
            }.getType());
        }
    }

    //根据选择的格式获取格式后缀
    private String getFormat() {
        String format = AudioFormat.MP3.getSuffix();
        if (selFormat.equals("mp3")) {
            format = AudioFormat.MP3.getSuffix();
        } else if (selFormat.equals("wav")) {
            format = AudioFormat.WAV.getSuffix();
        } else if (selFormat.equals("aac")) {
            format = AudioFormat.AAC.getSuffix();
        } else if (selFormat.equals("flac")) {
            format = AudioFormat.FLAC.getSuffix();
        } else if (selFormat.equals("m4a")) {
            format = AudioFormat.M4A.getSuffix();
        }
        return format;
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放音频
        mediaPlayer.seekTo(1);
        mDataBinding.ivAudioPlay.setImageResource(R.drawable.zanting1);
        mediaPlayer.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogFormatRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogFormatRenameConfirm);
        TextView dialogFormat = inflate.findViewById(R.id.tvDialogFormat);
        dialogRename = inflate.findViewById(R.id.etDialogFormatRename);
        String fileName = FileUtils.getFileName(audioPath);
        int index = fileName.indexOf(".");
        String startFormat = fileName.substring(index + 1, fileName.length());
        if (selFormat.isEmpty()) {
            dialogFormat.setText("." + startFormat);
        } else {
            dialogFormat.setText("." + selFormat);
        }
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private void formatTurnDialog() {
        myFormatTurnDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format_turn, null);
        myFormatTurnDialog.setContentView(inflate);
        myFormatTurnDialog.setCancelable(false);
        Window dialogWindow = myFormatTurnDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        dialogFormatTurnTitle = inflate.findViewById(R.id.tvDialogFormatTurnTitle);
        dialogFormatTurnText = inflate.findViewById(R.id.tvDialogFormatTurnText);
        dialogFormatPro = inflate.findViewById(R.id.tvDialogFormatPro);
        dialogFormatTurnComp = inflate.findViewById(R.id.tvDialogFormatTurnComp);
        pbFormat = inflate.findViewById(R.id.pbFormat);
        dialogFormatTurnComp.setOnClickListener(this);

    }

    private void clearFormat() {
        mDataBinding.tvFormatWav.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatMp3.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatFlac.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatAac.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatM4a.setBackgroundResource(R.drawable.shape_format);
    }

}